package com.wx.wxpush.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.vdurmont.emoji.EmojiParser;
import com.wx.wxpush.entiy.*;
import com.wx.wxpush.mapper.CornTaskMapper;
import com.wx.wxpush.mapper.UserInfoMapper;
import com.wx.wxpush.service.TemplateService;
import com.wx.wxpush.service.UserInfoService;
import com.wx.wxpush.util.CronUtil;
import com.wx.wxpush.util.ResultVO;
import com.wx.wxpush.util.WxOpenidInfo;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.io.UnsupportedEncodingException;
import java.sql.ResultSet;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.wx.wxpush.util.CronUtil.getCronToDate;

@RestController
@RequestMapping("/openid")
public class TemplateController {

    private static final Logger logger = LoggerFactory.getLogger(TemplateController.class);

    @Autowired
    private TemplateService templateService;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private CornTaskMapper cornTaskMapper;

    //获取access_token，access_token是公众号的全局唯一接口调用凭据
    @ResponseBody
    public static Constast getAccessToken(@RequestParam("appId") String appId
            ,@RequestParam("secret") String secret) {
        RestTemplate restTemplate = new RestTemplate();
        Map<String, String> map = new HashMap<>();
        map.put("AppId",appId);
        map.put("AppSecret",secret);
        //调用微信公众号接口
        ResponseEntity<String> forEntity = restTemplate.getForEntity("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={AppId}&secret={AppSecret}", String.class, map);
        String body = forEntity.getBody();
        JSONObject jsonObject = JSON.parseObject(body);
        String access_token = jsonObject.getString("access_token");
        String expires_in = jsonObject.getString("expires_in");//时效--7200s
        Constast constast = new Constast();
        constast.setAccess_token(access_token);
        return constast;
    }


    //获取用户列表的openid
    @RequestMapping("/list")
    public WeixinUserList getUserOpenIdList(@RequestParam("appid") String appId
            ,@RequestParam("secret") String secret) {
        //获取最新的access_token
        String accessToken = TemplateController.getAccessToken(appId,secret).getAccess_token();
        RestTemplate restTemplate = new RestTemplate();
        WeixinUserList openIdList = null;
        synchronized (this) {
            try {
                //循环获取用户openid列表--一次获取10000
                String nextOpenid = null;
                do {
                    //微信公众号获取用户列表信息接口地址
                    // 获取 https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
                    String requestUrl = null;
                    if (StringUtils.isBlank(nextOpenid)) {
                        requestUrl = new StringBuffer().append("https://api.weixin.qq.com/cgi-bin/user/get?access_token=").append(accessToken).toString();
                    } else {
                        requestUrl = new StringBuffer().append("https://api.weixin.qq.com/cgi-bin/user/get?access_token=")
                                .append(accessToken).append("&next_openid=").append(nextOpenid).toString();
                    }

                    openIdList = restTemplate.getForObject(requestUrl, WeixinUserList.class);
                    if (openIdList != null && openIdList.getErrcode() == 0) {
                        //获取用户关注列表对象
                        WxOpenidInfo data = openIdList.getData();
                        if (data != null) {
                            //获取当前循环的openid--10000条
                            List<String> openid = data.getOpenid();
                            System.out.println(openid+"openididiididi");
                            if (openid != null && openid.size() > 0) {
                                for (int i = 0; i < openid.size(); i += 100) {
                                    int toIndex = 100;
                                    if (i + 100 > openid.size()) {
                                        // 注意下标问题
                                        toIndex = openid.size() - i;
                                    }
                                    //循环100次，每次拿到openid列表中的集合下标;例如：(0,100),(100,200)
                                    List<String> sendList = openid.subList(i, i + toIndex);
                                    //每次insert---100条
                                   // templateService.delete();
                                    Thread.sleep(1000);
                                   // int num = templateService.insertForeach(sendList);

                                    //templateService.delete();
                                }
                            }
                        }
                        //拉取列表的最后一个用户的OPENID
                        nextOpenid = openIdList.getNext_openid();
                        System.out.println(nextOpenid);
                    } else {
                        openIdList.setErrcode(40000);
                        openIdList.setErrmsg("获取关注用户列表失败");
                        String url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
                        return openIdList;
                    }
                } while (openIdList.getCount() > 0);
            } catch (Exception e) {
                openIdList.setErrcode(40000);
                openIdList.setErrmsg("获取用户列表失败");
                return openIdList;
            }
        }
        return openIdList;
    }

    @PostMapping("/userifo")
    public ResultVO userIfo(@RequestParam("appid") String appId,@RequestParam("secret") String secret
            ,@RequestParam("code") String code) throws UnsupportedEncodingException {
        //https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx3e4673eaece40b43&redirect_uri=https%3A%2F%2Fi.samt.top%2F%23%2Fpages%2Fcode%2Fcode&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect
        String url=new StringBuffer().append("https://open.weixin.qq.com/connect/oauth2/authorize?appid=").append(appId) +
                "&redirect_uri=&response_type=code&scope=SCOPE&state=STATE#wechat_redirect";
        String u="https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code"
                .replace("APPID", appId).replace("SECRET", secret).replace("CODE", code);

        RestTemplate restTemplate = new RestTemplate();
        Map<String, String> map = new HashMap<>();
        map.put("APPID",appId);
        map.put("SECRET",secret);
        map.put("CODE",code);
        System.out.println(appId+secret+code+"获取 到的appid");
        ResponseEntity<String> forEntity = restTemplate.getForEntity("https://api.weixin.qq.com/sns/oauth2/access_token?appid={APPID}&secret={SECRET}&code={CODE}&grant_type=authorization_code", String.class, map);
        String body = forEntity.getBody();
        JSONObject jsonObject = JSON.parseObject(body);
        String access_token = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");
        AccessToken accessToken=new AccessToken();
        accessToken.setAccess_token(access_token);
        accessToken.setOpenid(openid);
        //调用获取逆臣接口 需要access_token  openid
        //https://api.weixin.qq.com/sns/userinfo?access_token=60_BF0H-8z-XVHrGQ-ipZZJ-phdjH1ARXLD_OKu1ucun9EuZvd0G31qXsu5YBwK6JBownCyOJ8q7FV4Np1tbIxy6K79bRWXYJyLJxUi7empj_A&openid=o7Rzm6Kzd3QhwBoPaPVnky_htvQU&lang=zh_CN
        System.out.println(access_token+openid+"token");

        map.put("token",access_token);
        map.put("openid",openid);
        ResponseEntity<String> forEntity1 = restTemplate.getForEntity("https://api.weixin.qq.com/sns/userinfo?access_token={token}&openid={openid}&lang=zh_CN", String.class, map);
       //处理乱码

        String body1 = forEntity1.getBody();
        JSONObject jsonObject1 = JSON.parseObject(body1);
        String nickname = jsonObject1.getString("nickname");
        nickname = new String(nickname.getBytes("ISO-8859-1"), "UTF-8");

//        EmojiParser.parseToAliases(nickname);
        String headimgurl = jsonObject1.getString("headimgurl");
        String openid1=jsonObject1.getString("openid");
        UserInfo userInfo=new UserInfo();
        userInfo.setNickname(nickname);
        userInfo.setOpenid(openid1);
        userInfo.setHeadimgurl(headimgurl);
        System.out.println(userInfo+"usern");
        //查询数据库有无此用户 有的话不插入
        if(userInfoService.selectByopenid(openid1)!=null){
            return ResultVO.ok(userInfo);

        }else{
        int i=userInfoService.insertUser(userInfo);
        if(i!=1){
            userInfo.setNickname("你的头像是表情包");
            userInfoService.insertUser(userInfo);
        }
        }
        return  ResultVO.ok(userInfo);

    }
//    @RequestMapping("/userinfolist")
//    public List<UserInfo> getUserinfo(){
//        return userInfoService.selectAll();
//    }

    @GetMapping("/userinfolist")
    public ResultVO getUserinfo(){
       List<UserInfo> userInfos= userInfoService.selectAll();
        return ResultVO.ok(userInfos);
    }
//    @RequestMapping("/pagelist")
//    public  PageInfo<UserInfo> pageQuery(@RequestParam("page")int page,@RequestParam("pagesize")int pagesize) {
//        PageInfo<UserInfo> queryResult = userInfoService.selectAllPage(page, pagesize);
//        return queryResult;
//    }

    @GetMapping("/pagelists")
    public ResultVO pageQuerys(@RequestParam("page")int page,@RequestParam("pagesize")int pagesize) {
        //页数  页数量
        PageHelper.startPage(page, pagesize);
        //查询数据
        List<UserInfo> userInfos= userInfoService.selectAll();
        //分页查询
        PageInfo<UserInfo> CrmReportPageInfo = new PageInfo<>(userInfos);
        return ResultVO.ok(CrmReportPageInfo);
    }

    //根据昵称来查询openid
    @GetMapping("/selectByNick")
    public ResultVO selectByNick(@RequestParam("nickname") String nickname){
        UserInfo userInfos= userInfoService.selectByNick(nickname);
        return ResultVO.ok(userInfos);
    }

    @ApiOperation(value = "获取用户定义模板列表", notes = "openid")
    @GetMapping("/tenpList")
    public ResultVO setCronNightStatus(@RequestParam("openid") String openid) throws ParseException {

        List<TemplateData> list1=new ArrayList<>();
        if(openid.equals(null) || openid.equals("")){
            return ResultVO.fail("无openid");
        }
        TemplateData list=userInfoMapper.selectTempList(openid);


        //System.out.println(list.getBirthday()+"1111111111111"+getCronToDate(list.getCronmoring())+list.getCronmoring());


        //System.out.println(list.getCronmoring().substring(5)+"截取");

//        list.setCronmoring(getCronToDate(list.getCronmoring()));
//        list.setCornnight(getCronToDate(list.getCornnight()));
//        Date time = getCronToDate(list.getCronmoring());
//        Date time2 = getCronToDate(list.getCornnight());
//
//        SimpleDateFormat sdf1 = new SimpleDateFormat("hh:mm", Locale.US);
//        TimeZone tz = TimeZone.getTimeZone("GMT+8");
//        sdf1.setTimeZone(tz);
//        sdf1.format(time);
//        sdf1.format(time2);
//        System.out.println(sdf1.format(time));
//        list.setCronmoring(sdf1.format(time));
//        list.setCornnight(sdf1.format(time2));
        return ResultVO.ok(list);
    }



}